﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MvcEngine.ItemList.Repositories;
using MvcEngine.LinqToSqlProvider;
using MvcEngine.ItemList.Models.Entities;
using MvcEngine.Core;
using Entities = MvcEngine.ItemList.Models.Entities;

namespace MvcEngine.ItemList.LinqToSqlProvider
{
    public class ItemListRepository : BaseGuidRepository<Entities.ItemList, Entities.ItemList>, IItemListRepository
    {
        public ItemListRepository(IDataContextFactory factory)
            :base(factory)
        {            
        }

        public override void Add(Entities.ItemList entity)
        {
            UpdateCreatedDate(entity);
            base.Add(entity);
        }

        public void Update(Entities.ItemList entity)
        {
            var itemList = Get(entity.Id);

            itemList.Title = entity.Title;
            itemList.Description = entity.Description;
            itemList.ShortContent = entity.ShortContent;
            itemList.Content = entity.Content;

            UpdateModifiedDate(itemList);

            context.SubmitChanges();
        }

        private void UpdateModifiedDate(Entities.ItemList entity)
        {
            entity.ModifiedBy = UserContext.Current.User.Id;
            entity.ModifiedDate = DateTime.Now;
        }

        private void UpdateCreatedDate(Entities.ItemList entity)
        {
            entity.CreatedBy = UserContext.Current.User.Id;
            entity.CreatedDate = DateTime.Now;
            UpdateModifiedDate(entity);
        }
    }
}
